package com.kipling.kio.demo.server;

import java.nio.ByteBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

import com.kipling.kio.core.exception.KioDecodeException;
import com.kipling.kio.core.intf.KioHandler;
import com.kipling.kio.core.intf.Packet;
import com.kipling.kio.demo.common.Command;
import com.kipling.kio.demo.common.ShowcasePacket;
import com.kipling.kio.demo.common.intf.AbsShowcaseBsHandler;
import com.kipling.kio.demo.server.handler.P2PReqHandler;
import com.kipling.kio.demo.server.handler.PushMsgReqHandler;
import com.kipling.kio.json.Json;
import com.kipling.kio.server.ServerGroupContext;
import com.kipling.kio.server.intf.ServerKioHandler;

/** 
 * @author KiplingLee E-mail: kiplinglee@163.com
 * @version 创建时间：2017年5月5日 上午10:11:50 
 * 
 */
public class ShowcaseServerKioHandler extends
		ServerKioHandler< Packet, Object> implements KioHandler< Packet, Object> {

	private static Map<Byte, AbsShowcaseBsHandler<?>> handlerMap = new HashMap<Byte, AbsShowcaseBsHandler<?>>();
	static
	{
		handlerMap.put(Command.MSG_REQ.getCode(), new P2PReqHandler());
		handlerMap.put(Command.PUSH_REQ.getCode(), new PushMsgReqHandler());
		
		
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

	@Override
	public Object handler(Packet packet,
			ServerGroupContext<Packet, Object> serverGroupContext)
			throws Exception {
		if(packet==null){
			return null;
		}
		Byte type = packet.getType();
		AbsShowcaseBsHandler<?> showcaseBsHandler = handlerMap.get(type);
		if (showcaseBsHandler == null)
		{
			return null;
		}
		showcaseBsHandler.handler(packet,serverGroupContext);
		return null;
	}

	@Override
	public ShowcasePacket decode(ByteBuffer buffer) throws KioDecodeException {
		ShowcasePacket packet = null;
		buffer.flip();
        try {
			String received = Charset.forName(ShowcasePacket.CHARSET).newDecoder().decode(buffer).toString();
			System.out.println("received:"+received);
			packet = Json.toBean(received, ShowcasePacket.class);
			
		} catch (CharacterCodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        return packet;
	}


}
